package com.huayu.languo.common.util;

import cn.hutool.crypto.SecureUtil;
import com.huayu.languo.model.excp.SystemException;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

/**
 * @author 刘雄康
 * @version v1.0
 * @description 签名工具类
 * @date 2019年03月15日
 */
public final class SignUtil {

    /**
     * 加密算法RSA
     */
    private static final String KEY_ALGORITHM = "RSA";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    private SignUtil() {
        super();
    }

    /**
     * 获得参数格式化字符串
     * 参数名按字典升序排序，小写在后面
     *
     * @param params
     */
    public static String getFormatParams(Map<String, Object> params) {
        Collection<String> keyset = params.keySet();
        List<String> list = new ArrayList<>(keyset);
        Collections.sort(list);
        StringBuilder ret = new StringBuilder();
        for (String key : list) {
            if (!"sign".equals(key) && !"apisign".equals(key)) {
                Object value = params.get(key);
                if (null != value && !"".equals(value)) {
                    ret.append(key).append("=").append(value).append("&");
                }
            }
        }
        String signParamStr = "";
        if (ret.length() > 0) {
            signParamStr = ret.substring(0, ret.length() - 1);
        }
        return signParamStr;
    }

    public static boolean verifyMd5Sign(Map<String, Object> params, String signed) {
        String formatParams = getFormatParams(params);
        String sign = SecureUtil.md5(formatParams);
        return signed.equalsIgnoreCase(sign);
    }

    /**
     * java端公钥加密方法
     * data:需要加密的数据
     * PUBLICKEY:公钥
     */
    public static String encryptedDataOnJava(String data, String pubLicKey) {
        return Base64.encodeBase64String(encryptByPublicKey(data.getBytes(Charset.forName("utf-8")), pubLicKey));
    }

    /**
     * 公钥加密
     *
     * @param data      源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) {
        try {
            byte[] keyBytes = Base64.decodeBase64(publicKey);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicK);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }
}
